package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.mindrot.jbcrypt.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);

        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());

        //用户不存在
        if (user==null){
            log.info("[登录]失败，user:{}",param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //判断加密方式
        else if(user.getPassword().startsWith("{md5}")){
            String md5Pass = DigestUtils.md5DigestAsHex(param.getPassword().getBytes());
            if (user.getPassword().equals("{md5}"+md5Pass)){
                log.info("[登录]成功，user:{}",param);
                request.getSession().setAttribute("user",user);
                return new Result(true, MessageConst.LOGIN_SUCCESS);
            }
        }
        else if (user.getPassword().startsWith("{bcrypt}")){
            String bcryptPass=BCrypt.hashpw(param.getPassword(),BCrypt.gensalt());
            if (!BCrypt.checkpw(user.getPassword(),bcryptPass)){
                log.info("[登录]成功，user:{}",param);
                request.getSession().setAttribute("user",user);
                return new Result(true, MessageConst.LOGIN_SUCCESS);
            }
        }
        else if(user.getPassword().equals(param.getPassword())){
            log.info("[登录]成功，user:{}",param);
            request.getSession().setAttribute("user",user);
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        log.info("[登录]失败，user:{}",param.getUsername());
        return new Result(false, MessageConst.LOGIN_FAIL);
    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().invalidate();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }
}
